import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { useUserStore } from './user'

interface PurchasedProduct {
  id: string;
  product_id: string;
  name: string;
  is_purchased: boolean;
  click_url?: string;
  image_url?: string;
  expire_time?: string;
  status?: string;
  product: {
    id: string;
    product_id: string;
    name: string;
    title: string;
    description: string;
    image_url: string;
    price: number;
    click_url?: string;
    version: string;
    category: number
  }
  duration: number
  phone: string
  purchased_time: string
}

interface ProductCheckResponse {
  is_purchased: boolean;
  click_url?: string;
}

export const usePurchasedStore = defineStore('purchased', () => {
  const purchasedProducts = ref<PurchasedProduct[]>([])
  const loading = ref(false)
  const hasCompanyCard = ref(false)
  const showShareButton = ref(false)
  const userStore = useUserStore()

  // 监听用户信息变化
  watch(() => userStore.userInfo, (newUserInfo) => {
    console.log('[关键节点] 用户信息变化回调触发', {
      hasPhone: !!newUserInfo?.phone,
      time: new Date().toISOString()
    })

    if (newUserInfo?.phone) {
      fetchPurchasedProducts(true)
    } else {
      // 用户登出时清空数据
      purchasedProducts.value = []
      hasCompanyCard.value = false
      showShareButton.value = false
      // 清除缓存
      uni.removeStorageSync('purchasedProducts')
    }
  })

  // 获取已购买商品列表
  async function fetchPurchasedProducts(force = false) {
    if (!userStore.userInfo?.phone || !userStore.userInfo?.access_token) {
      console.log('[关键节点] 用户未登录或未绑定手机号', {
        time: new Date().toISOString()
      })
      return
    }

    loading.value = true
    try {
      // 如果不是强制刷新，尝试从缓存获取数据
      if (!force) {
        const cachedData = uni.getStorageSync('purchasedProducts')
        if (cachedData) {
          purchasedProducts.value = JSON.parse(cachedData)
          console.log('[关键节点] 使用缓存数据', {
            productsCount: purchasedProducts.value.length,
            time: new Date().toISOString()
          })
        }
      }

      const res = await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/user-products/',
        method: 'GET',
        header: {
          'Authorization': `Bearer ${userStore.userInfo.access_token}`,
          'Content-Type': 'application/json'
        },
        data: {
          phone: userStore.userInfo.phone,
          timestamp: Date.now(),
          debug: true
        }
      })

      const { data, statusCode } = res

      if (statusCode === 200 && Array.isArray(data)) {
        // 获取每个商品的最新状态
        const productsWithStatus = await Promise.all(
          (data as PurchasedProduct[]).map(async (product) => {
            const status = await checkProductStatus(product.product_id)
            console.log(status,'status1232125')
            return {
              ...product,
              is_purchased: status.is_purchased,
              // click_url: status.click_url
            }
          })
        )
        console.log(productsWithStatus, 555567987964646)
        purchasedProducts.value = productsWithStatus
        // 更新缓存
        uni.setStorageSync('purchasedProducts', JSON.stringify(productsWithStatus))

        // 检查是否有企业名片产品
        console.log('[关键节点] 检查是否有企业名片产品', {
          products: purchasedProducts.value,
          time: new Date().toISOString()
        })
        hasCompanyCard.value = purchasedProducts.value.some(product =>
          product.product_id == '1' && product.status == '1'
        )

        // 更新分享按钮状态
        await updateShareButtonStatus()

        console.log('[关键节点] 更新购买记录成功', {
          productsCount: productsWithStatus.length,
          hasCompanyCard: hasCompanyCard.value,
          showShareButton: showShareButton.value,
          time: new Date().toISOString()
        })
      } else if (statusCode === 401) {
        // 未授权，需要重新登录
        uni.showToast({
          title: '请重新登录',
          icon: 'none'
        })
        // 触发重新登录流程
        userStore.logout()
      } else {
        throw new Error(`请求失败: ${statusCode}`)
      }
    } catch (error) {
      console.error('获取已购商品列表失败:', error)
      uni.showToast({
        title: '获取商品列表失败',
        icon: 'none'
      })

      // 如果请求失败，尝试使用缓存数据
      const cachedData = uni.getStorageSync('purchasedProducts')
      if (cachedData) {
        purchasedProducts.value = JSON.parse(cachedData)
        uni.showToast({
          title: '使用缓存数据',
          icon: 'none'
        })
      }
    } finally {
      loading.value = false
    }
  }

  // 检查单个商品购买状态
  async function checkProductStatus(productId: string): Promise<ProductCheckResponse> {
    if (!userStore.userInfo?.access_token) {
      return { is_purchased: false }
    }

    try {
      const res = await uni.request({
        url: `https://52d47b77.r34.cpolar.top/api/product-check/?product_id=${productId}&phone=${userStore.userInfo.phone}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${userStore.userInfo.access_token}`
        }
      })
      console.log(res, 5555879646467777)
      const { data, statusCode } = res
      if (statusCode === 200) {
        data as ProductCheckResponse
          return { is_purchased: true }
      }
      return { is_purchased: false }
    } catch (error) {
      console.error('检查商品状态失败:', error)
      return { is_purchased: false }
    }
  }

  // 更新单个商品状态
  async function updateProductStatus(productId: string) {
    const status = await checkProductStatus(productId)
    console.log(status, 555587964646777711111)
    const index = purchasedProducts.value.findIndex(p => p.product_id === productId)

    if (index !== -1) {
      purchasedProducts.value[index] = {
        ...purchasedProducts.value[index],
        is_purchased: status.is_purchased,
        click_url: status.click_url
      }

      // 更新缓存
      uni.setStorageSync('purchasedProducts', JSON.stringify(purchasedProducts.value))

      // 如果是企业名片产品，更新相关状态
      if (productId === 'company_card') {
        hasCompanyCard.value = status.is_purchased
        await updateShareButtonStatus()
      }
    }
  }

  // 更新分享按钮状态
  async function updateShareButtonStatus() {
    if (!hasCompanyCard.value) {
      showShareButton.value = false
      return
    }

    try {
      const res = await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/company-cards/check-exists/',
        method: 'GET',
        header: {
          'Authorization': `Bearer ${userStore.userInfo?.access_token}`
        }
      })

      showShareButton.value = res.statusCode === 200
      console.log('[关键节点] 更新分享按钮状态', {
        showShareButton: showShareButton.value,
        time: new Date().toISOString()
      })
    } catch (error) {
      console.error('检查企业信息失败:', error)
      showShareButton.value = false
    }
  }

  // 处理商品点击
  async function handleProductClick(product: PurchasedProduct) {
    console.log('[关键节点] 用户点击产品', {
      productId: product.id,
      name: product.name,
      hasLink: !!product.click_url,
      time: new Date().toISOString()
    })

    // 重新检查商品状态
    const status = await checkProductStatus(product.product_id)
console.log(status,'status1232125')
    if (!status.is_purchased) {
      uni.showToast({
        title: '请先购买该商品',
        icon: 'none'
      })
      return
    }

    if (status.click_url) {
      console.log('[关键节点] 准备跳转到:', status.click_url)
      uni.navigateTo({
        url: status.click_url,
        fail: (err) => {
          console.error('跳转失败', {
            error: err,
            url: status.click_url,
            time: new Date().toISOString()
          })
          uni.showToast({
            title: '跳转失败，请稍后重试',
            icon: 'none'
          })
        }
      })
    } else {
      uni.showToast({
        title: '该产品未配置跳转链接',
        icon: 'none'
      })
    }
  }

  // 定时刷新数据
  let refreshTimer: number | undefined
  function startAutoRefresh() {
    if (refreshTimer) clearInterval(refreshTimer)
    refreshTimer = setInterval(() => {
      if (userStore.userInfo?.phone) {
        console.log('[关键节点] 定时刷新购买记录', {
          time: new Date().toISOString()
        })
        fetchPurchasedProducts(true)
      }
    }, 5 * 60 * 1000) // 每5分钟刷新一次
  }

  // 停止定时刷新
  function stopAutoRefresh() {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = undefined
    }
  }

  return {
    purchasedProducts,
    loading,
    hasCompanyCard,
    showShareButton,
    fetchPurchasedProducts,
    checkProductStatus,
    updateProductStatus,
    handleProductClick,
    startAutoRefresh,
    stopAutoRefresh
  }
})
